package com.zzk.protect.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzk.protect.common.CommonResult;
import com.zzk.protect.pojo.ConstantType;
import com.zzk.protect.service.ConstantTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/constantType")
public class ConstantTypeController {
    @Autowired
    private ConstantTypeService constantTypeService;
    // 获取列表（分页）
    @GetMapping("/list")
    public CommonResult list() {
        QueryWrapper<ConstantType> queryWrapper = new QueryWrapper<>();
        List<ConstantType> list = constantTypeService.list(queryWrapper);
        return CommonResult.success(list);
    }
    @PostMapping("/add")
    public CommonResult add(@RequestBody ConstantType constantType) {
        // 检查code是否已存在
        QueryWrapper<ConstantType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", constantType.getCode());
        if (constantTypeService.count(queryWrapper) > 0) {
            return CommonResult.failed("编码已存在");
        }
        constantType.setIsDeleted(1); // 默认启用状态

        return CommonResult.success(constantTypeService.save(constantType));
    }
    //批量删除
    @DeleteMapping("/delete/{id}")
    public CommonResult deleteBatch(@RequestBody @PathVariable Long id){
        return CommonResult.success(constantTypeService.removeById(id));
    }
    // 切换状态
    @PostMapping("/status")
    public CommonResult status(@RequestBody ConstantType constantType) {
        ConstantType entity = new ConstantType();
        entity.setId(constantType.getId());
        entity.setIsDeleted(constantType.getIsDeleted());
        return CommonResult.success(constantTypeService.updateById(entity));
    }
    @PostMapping("/update")
    public CommonResult update(@RequestBody ConstantType constantType) {
        // 检查code是否已存在（排除自己）
        QueryWrapper<ConstantType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", constantType.getCode());
        queryWrapper.ne("id", constantType.getId());
        if (constantTypeService.count(queryWrapper) > 0) {
            return CommonResult.failed("编码已存在");
        }
        return CommonResult.success(constantTypeService.updateById(constantType));
    }
    @GetMapping("/select")
    public CommonResult selectByIdOrName(@RequestBody  Object param) {
        try {
            List<ConstantType> result = constantTypeService.selectByIdOrName(param);
            return CommonResult.success(result);
        } catch (Exception e) {
            return CommonResult.failed("查询失败: " + e.getMessage());
        }
    }

}
